package com.zyz.study.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class WeatherService {
    // 和风天气 API 密钥，请替换为你自己的！！！
    private static final String API_KEY = "f036c3b0aa3d4223804cabdc29e392bb"; // 请替换成你自己的 key

    // 和风天气 实时天气 API 地址
    private static final String BASE_URL = "https://q463yvwkqx.re.qweatherapi.com/v7/weather/now?location=%s&key=%s";

    // 传入城市代码，比如北京是 "101010100"
    public JsonNode getWeatherV2(String locationCode) throws Exception {
        // 1. 拼接完整的请求 URL：location=城市代码&key=API_KEY
        String url = String.format(BASE_URL, locationCode, API_KEY);

        // 2. 创建 HttpClient
        var httpClient = HttpClients.createDefault();

        // 3. 创建 RestTemplate 的 HTTP 工厂
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        // 4. 使用 RestTemplate 发送 GET 请求
        RestTemplate restTemplate = new RestTemplate(factory);
        String response = restTemplate.getForObject(url, String.class);

        // 5. 解析返回的 JSON 数据
        JsonNode jsonNode = new ObjectMapper().readTree(response);

        log.info("getWeatherV2 response={}", response);
        // 6. 返回 JSON 数据，你可以进一步解析，比如温度、天气状况等
        return jsonNode;
    }
}
